package com.nwpu.bigdata.service.impl;

import java.util.List;
import java.util.Map;

import com.nwpu.bigdata.model.FaultKeyExtend;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nwpu.bigdata.dao.EsLogDao;
import com.nwpu.bigdata.dao.mapper.ExceptLogMapper;
import com.nwpu.bigdata.dto.BackendResult;
import com.nwpu.bigdata.exception.NoLogExcetion;
import com.nwpu.bigdata.model.ExceptLog;
import com.nwpu.bigdata.service.ESLogService;

/**
 * @author carlin
 */
@Service
public class ESLogServiceImpl implements ESLogService {
	private static Logger logger = LoggerFactory.getLogger("com.nwpu.bigdata");
	private final EsLogDao esLogDao;

	private final ExceptLogMapper exceptLogMapper;

	@Autowired
	public ESLogServiceImpl(EsLogDao esLogDao, ExceptLogMapper exceptLogMapper) {
		this.esLogDao = esLogDao;
		this.exceptLogMapper = exceptLogMapper;
	}

	@Override
	public boolean writeLogToDB(String index, String type,
								FaultKeyExtend faultKeyExtend, String[] includes, String[] excludes)
			throws NoLogExcetion {
		List<ExceptLog> exceptLogs = esLogDao.searchLog(index, type, faultKeyExtend, includes, excludes);
		if (exceptLogs == null || exceptLogs.isEmpty()) {
			throw new NoLogExcetion("Data Null Exception !");
		}
		int sucessfulNum = exceptLogMapper.insertList(exceptLogs);
		logger.info("the insert mysql errorLog number : {}", sucessfulNum);
		return true;
	}

	@Override
	public BackendResult<List<ExceptLog>> getAssignLogByUser(String index, String type,
															 Map<String, String[]> conditions, DateTime startTime,
															 DateTime endTime, FaultKeyExtend faultKeyExtend) {
		List<ExceptLog> exceptLogs = esLogDao.searchLogByUser(index, type, conditions, startTime, endTime, faultKeyExtend);

		if (exceptLogs == null || exceptLogs.size() == 0) {
			logger.info("the search command has not data return! please check the conditions");
			return new BackendResult<>(false, "the search command has not data return! please check the conditions");
		}
		return new BackendResult<>(true, exceptLogs);
	}

}
